package com.share.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * author:caifan
 * date:2019/7/4
 */
@RestController
@RequestMapping("/rest/file")
@Slf4j
public class FileController {

    @RequestMapping(value = "/singleUpload", method = RequestMethod.POST)
    public String singleFileUpload(@RequestParam("file")MultipartFile file) {
        if (file.isEmpty()) {
            return "file is empty";
        }
        String originalFilename = file.getOriginalFilename();
        originalFilename = getFileName() + "-" + originalFilename;
        File dest = new File(System.getProperty("user.home") + File.separator + originalFilename);

        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            log.error("file upload error:{}", e.getMessage());
        }
        return "file upload success";
    }

    @RequestMapping(value = "/multiUpload", method = RequestMethod.POST)
    public String manyFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                log.info( "file is empty");
                continue;
            }
            String originalFilename = file.getOriginalFilename();
            originalFilename = getFileName() + "-" + originalFilename;
            File dest = new File("D:/test" + File.separator + originalFilename);

            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                log.error("file upload error:{}", e.getMessage());
            }
        }
        return "file upload success";
    }

    @RequestMapping(value = "/download", method = RequestMethod.POST)
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String filename = request.getParameter("fileName");
        if (StringUtils.isEmpty(filename)) {
            return "filename is null";
        }
        String realPath = "D:/test";
        File file = new File(realPath, filename);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        response.setContentType("application/force-download");//强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + filename);
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int len = 0;
            while ((len = bis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            bos = new BufferedOutputStream(os);
        } catch (Exception e) {
            log.error("file download fail error:{}", e.getMessage());
            return "file download fail";
        } finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (Exception e) {
                    log.error("write file close error:{}", e.getMessage());
                }
            }
            if (null != fis) {
                try {
                    fis.close();
                } catch (Exception e) {
                    log.error("stream close error:{}", e.getMessage());
                }
            }
            if (null != bis) {
                try {
                    bis.close();
                } catch (Exception e) {
                    log.error("stream close error:{}", e.getMessage());
                }
            }

        }
        return "file download success";
    }


    private String getFileName() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime localDateTime = LocalDateTime.now();
        return localDateTime.format(formatter);
    }
}
